package com.zhangye.test.api;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhangye.test.mapper.AccountMapper;
import com.zhangye.test.model.Admin;
import com.zhangye.test.model.SafeSession;
import com.zhangye.test.model.SmsSession;
import com.zhangye.test.service.AdminService;
import com.zhangye.test.service.BusinessService;
import com.zhangye.test.service.RedisService;
import com.zhangye.test.service.SafeSessionService;
import com.zhangye.test.service.SendMsgService;
import com.zhangye.test.service.SmsSessionService;
import com.zhangye.test.util.AES;
import com.zhangye.test.util.SensitivewordFilter;
import com.zhangye.test.util.StringUtils;

/**
 * 注册
 * 
 * @author 作者：张叶
 * @version 创建时间：2016年7月27日 下午1:40:49
 */
@Controller
@RequestMapping("api/register")
public class RegisterApi {
	Logger logger = LoggerFactory.getLogger(RegisterApi.class);

	@Autowired
	private SafeSessionService safeSessionService;// 安全登录
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private BusinessService businessService;
	@Autowired
	private AdminService adminService;
	@Autowired
	private SmsSessionService smsSessionService;
	@Autowired
	private RedisService redisService;
	@Autowired
	private SendMsgService sendMsgService;


	
	/**
	 * 微信注销绑定
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  下午1:52:23
	 */
	@ResponseBody
	@RequestMapping(value = "/wechatCancel", method = RequestMethod.GET)
	public ApiResult wechatCancel(HttpServletRequest request) {
		ApiResult result = new ApiResult();
		Admin admin = safeSessionService.getCurrent(request);
		if(admin != null){
			admin.setWechatOpenId("");
			int i = adminService.updateAdmin(admin,0);
			if(i > 0){
				result.msg.status = 0;
				result.msg.desc = "解绑成功";
			}else {
				result.msg.status = 1;
				result.msg.desc = "系统错误，解绑成功";
			}
		} else {
			result.msg.status = 2;
			result.msg.desc = "当前登录已失效，请重新登录";
		}
		return result;
	}
	
	/**
	 * QQ注销绑定
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  下午1:52:23
	 */
	@ResponseBody
	@RequestMapping(value = "/qqCancel", method = RequestMethod.GET)
	public ApiResult qqCancel(HttpServletRequest request) {
		ApiResult result = new ApiResult();
		Admin admin = safeSessionService.getCurrent(request);
		if(admin != null){
			admin.setQqOpenId("");
			int i = adminService.updateAdmin(admin,0);
			if(i > 0){
				result.msg.status = 0;
				result.msg.desc = "解绑成功";
			}else {
				result.msg.status = 1;
				result.msg.desc = "系统错误，解绑成功";
			}
		} else {
			result.msg.status = 2;
			result.msg.desc = "当前登录已失效，请重新登录";
		}
		return result;
	}

	
	/**
	 * QQ注册绑定
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  下午1:52:23
	 */
	@ResponseBody
	@RequestMapping(value = "/qqRegister", method = RequestMethod.POST)
	public ApiResult qqRegister(HttpServletRequest request,
			HttpServletResponse response, String telphone,String password,
			String smsCode , String qqOpenId) {
		ApiResult result = new ApiResult();
		if(telphone != null && !"".equals(telphone)
				&& password != null && !"".equals(password)
						&& smsCode != null && !"".equals(smsCode)
								&& qqOpenId != null && !"".equals(qqOpenId)){
			//判断微信是否绑定
			String where = " and qq_open_id = '" + qqOpenId + "'";
			List<Admin> list = adminService.selectWhere(where);
			if(list.size() == 0){
				// 2、判断手机号是否已存在
				Admin existAdmin = adminService.findByTelphone(telphone);
				if (existAdmin == null) {
					SmsSession ss = smsSessionService.findBySessionId(telphone);
					if (ss != null) {
//						try {
//							int reInt = smsService.verifySMSCode( ss.getSessionId(), smsCode);
//							if (reInt == 0) {
							if(smsCode.equals(ss.getSessionId())){
								// 添加记录
								Admin admin = new Admin();
								admin.setTelphone(telphone);
								admin.setUsername(telphone);
								admin.setPassword(DigestUtils.md5Hex(password));
								admin.setCreatedate(new Date());
								admin.setCounts(20);
								admin.setIsabled(1);
								admin.setQqOpenId(qqOpenId);
								int count = adminService.insertAdminAndAur(admin);// 保存会员信息
								if (count > 0) {
									String sessionId = getSessionId(request,
											response, telphone, password);
									result.data.put("sessionId", sessionId);
									result.msg.status = 0;
									result.msg.desc = "注册绑定成功";
								} else {
									result.msg.status = 1;
									result.msg.desc = "系统问题，注册绑定失败";
								}
							} else {
								result.msg.status = 2;
								result.msg.desc = "验证码输入错误！";
							}
//						} catch (Exception e) {
//							result.msg.status = 2;
//							result.msg.desc = "验证码输入错误！";
//						}
					} else {
						result.msg.status = 2;
						result.msg.desc = "验证码输入错误！";
					}
				} else {
					result.msg.status = 6;
					result.msg.desc = "手机号已存在！";
				}
			}else {
				result.msg.status = 4;
				result.msg.desc = "该账号已绑定手机号，手机号为：" + list.get(0).getTelphone();
			}
		} else {
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}

	
	/**
	 * 微信注册绑定
	 * 作者： 张叶
	 * 创建时间：2018年7月25日  下午1:52:23
	 */
	@ResponseBody
	@RequestMapping(value = "/wechatRegister", method = RequestMethod.POST)
	public ApiResult wechatRegister(HttpServletRequest request,
			HttpServletResponse response, String telphone,String password,
			String smsCode , String wechatOpenId) {
		ApiResult result = new ApiResult();
		if(telphone != null && !"".equals(telphone)
				&& password != null && !"".equals(password)
						&& smsCode != null && !"".equals(smsCode)
								&& wechatOpenId != null && !"".equals(wechatOpenId)){
			//判断微信是否绑定
			String where = " and wechat_open_id = '" + wechatOpenId + "'";
			List<Admin> list = adminService.selectWhere(where);
			if(list.size() == 0){
				// 2、判断手机号是否已存在
				Admin existAdmin = adminService.findByTelphone(telphone);
				if (existAdmin == null) {
					SmsSession ss = smsSessionService.findBySessionId(telphone);
					if (ss != null) {
//						try {
//							int reInt = smsService.verifySMSCode( ss.getSessionId(), smsCode);
//							if (reInt == 0) {
							if(smsCode.equals(ss.getSessionId())){
								// 添加记录
								Admin admin = new Admin();
								admin.setTelphone(telphone);
								admin.setUsername(telphone);
								admin.setPassword(DigestUtils.md5Hex(password));
								admin.setCreatedate(new Date());
								admin.setCounts(20);
								admin.setIsabled(1);
								admin.setWechatOpenId(wechatOpenId);
								int count = adminService.insertAdminAndAur(admin);// 保存会员信息
								if (count > 0) {
									String sessionId = getSessionId(request,
											response, telphone, password);
									result.data.put("sessionId", sessionId);
									result.msg.status = 0;
									result.msg.desc = "注册绑定成功";
								} else {
									result.msg.status = 1;
									result.msg.desc = "系统问题，注册绑定失败";
								}
							} else {
								result.msg.status = 2;
								result.msg.desc = "验证码输入错误！";
							}
//						} catch (Exception e) {
//							result.msg.status = 2;
//							result.msg.desc = "验证码输入错误！";
//						}
					} else {
						result.msg.status = 2;
						result.msg.desc = "验证码输入错误！";
					}
				} else {
					result.msg.status = 6;
					result.msg.desc = "手机号已存在！";
				}
			}else {
				result.msg.status = 4;
				result.msg.desc = "该账号已绑定手机号，手机号为：" + list.get(0).getTelphone();
			}
		} else {
			result.msg.status = 3;
			result.msg.desc = "参数不能为空";
		}
		return result;
	}

	
	/**
	 * 注册会员信息 
	 *  “type”:android/ios
	 * 作者： 张叶
	 * 创建时间：2018年6月28日  下午4:15:04
	 */
	@ResponseBody
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ApiResult register(HttpServletRequest request,
			HttpServletResponse response, String datas , String type) {
		ApiResult result = new ApiResult();
		if(type != null && !"".equals(type)){
			String reqParam = request.getParameter("datas");
			if(type.equals("android")){
				byte[] aes = AES.decrypt(StringUtils.parseHexStr2Byte(reqParam));
				try {
					reqParam = new String(aes, "utf-8");
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
			}
			JSONObject jasonObject = JSONObject.fromObject(reqParam);
			String telphone = (String) jasonObject.get("telphone");
			String password = (String) jasonObject.get("password");
			String code = (String) jasonObject.get("smsCode");
			// 判断参数是否为空
			if (telphone != null && password != null ) {
					Admin admin = new Admin();
					// 2、判断手机号是否已存在
					Admin existAdmin = adminService.findByTelphone(telphone);
					if (existAdmin != null) {
						result.msg.status = 3;
						result.msg.desc = "手机号已存在！";
					} else {
						//敏感词过滤
						SensitivewordFilter filter = new SensitivewordFilter();
						Set<String> set = filter.getSensitiveWord(jasonObject.toString(), 1);
						if(set.size()==0){
							SmsSession ss = smsSessionService.findBySessionId(telphone);
							if (ss != null) {
//								try {
//									int reInt = smsService.verifySMSCode( ss.getSessionId(), code);
//									if (reInt == 0) {
									if(code.equals(ss.getSessionId())){
										// 添加记录
										admin.setTelphone(telphone);
										admin.setUsername(telphone);
										admin.setPassword(DigestUtils.md5Hex(password));
										admin.setCreatedate(new Date());
										admin.setCounts(20);
										admin.setIsabled(1);
										int count = adminService.insertAdminAndAur(admin);// 保存会员信息
										if (count > 0) {
											String sessionId = getSessionId(request,
													response, telphone, password);
											result.data.put("sessionId", sessionId);
											result.msg.status = 0;
											result.msg.desc = "注册成功";
										} else {
											result.msg.status = 1;
											result.msg.desc = "系统问题，注册失败";
										}
									} else {
										result.msg.status = 2;
										result.msg.desc = "验证码输入错误！";
									}
//								} catch (Exception e) {
//									e.printStackTrace();
//								}
							} else {
								result.msg.status = 2;
								result.msg.desc = "验证码输入错误！";
							}
						} else {
							result.msg.desc = "内容有敏感词，请重新输入！";
							result.msg.status = 5;
						}
					}
			} else {
				result.msg.status = 4;
				result.msg.desc = "参数为空";
			}
		} else {
			result.msg.status = 4;
			result.msg.desc = "参数为空";
		}
		return result;
	}

	
	/**
	 * 发送短信验证码
	 * smsType: register:注册,findPwd:找回,login:登录,updatePwd:修改密码
	 * 作者： 张叶
	 * 创建时间：2018年6月28日  下午3:25:37
	 */
	@ResponseBody
	@RequestMapping(value = "/validate", method = RequestMethod.POST)
	public ApiResult validatedemo(String telphone,String code, String type,
			HttpServletRequest request) {
		ApiResult result = new ApiResult();
		String validate = redisService.get("ar.zhyell.com:api:imgValidate:" + type + ":" + telphone);
		if(validate != null && !"".equals(validate)){
			if (validate.equals(code)) {
				redisService.del("ar.zhyell.com:api:imgValidate:" + type + ":" + telphone);
				if (telphone == null) {// 手机号为空返回失败
					result.msg.status = 1;
					result.msg.desc = "手机号参数为空！";
				} else {
					if ("register".equals(type) || "findPwd".equals(type) || "login".equals(type) || "updatePwd".equals(type)) {
						if ("findPwd".equals(type)) {// 找回,
							Admin admin = adminService.findByTelphone(telphone);
							if (admin == null) {
								result.msg.status = 2;
								result.msg.desc = "手机号不存在";
								return result;
							}
						}
					} else {
						result.msg.status = 3;
						result.msg.desc = "发送短信类型不正确";
						return result;
					}
					try {
						if(isNumLegal(telphone)){
//							int reInt = smsService.sendMessage(telphone);
							int reInt = sendMsgService.sendMsg(telphone, 0);
							if (reInt != 1) {
								result.msg.status = 1;
								result.msg.desc = "发送失败！";
							} else {
								result.msg.status = 0;
								result.msg.desc = "发送成功！";
							}
						} else {
							result.msg.status = 5;
							result.msg.desc = "手机号不正确！";
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			} else {
				result.msg.status = 4;
				result.msg.desc = "验证码不正确，请重新输入！";
			}
		} else {
			result.msg.status = 6;
			result.msg.desc = "手机号与验证码不匹配";
		}
		return result;
	}
	

	/**
	 * 找回密码
	 * 
	 * @author 张叶
	 * @version 创建时间：2016年7月27日 下午1:41:25
	 */
	@ResponseBody
	@RequestMapping(value = "/findPassword", method = RequestMethod.POST)
	public ApiResult validateCaptcha(HttpServletRequest request,
			HttpServletResponse response, String datas) {

		ApiResult result = new ApiResult();
		result.msg.status = 1;
		result.msg.desc = "验证失败";
		String req = "";
		String reqParam = request.getParameter("datas");
		byte[] aes = AES.decrypt(StringUtils.parseHexStr2Byte(reqParam));
		try {
			req = new String(aes, "utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		JSONObject jasonObject = JSONObject.fromObject(req);
		String telphone = (String) jasonObject.get("telphone");
		String validateNum = (String) jasonObject.get("validateNum");
		String password = (String) jasonObject.get("password");

		if (telphone != null && telphone != "" && validateNum != null
				&& validateNum != "") {
			SmsSession ss = smsSessionService.findBySessionId(telphone);
			Admin admin = adminService.findByTelphone(telphone);
//			int reInt;
			if (admin != null) {
				if (ss != null) {
//					try {
//						reInt = smsService.verifySMSCode(ss.getSessionId(),
//								validateNum);
//						if (reInt == 0) {
						if(validateNum.equals(ss.getSessionId())){
							admin.setPassword(DigestUtils.md5Hex(password));
							int count = adminService.updateAdmin(admin,0);
							if (count > 0) {
								result.msg.status = 0;
								result.msg.desc = "修改成功！";
							} else {
								result.msg.status = 1;
								result.msg.desc = "系统错误，修改失败！";
							}
						} else {
							result.msg.status = 2;
							result.msg.desc = "验证码错误!";
						}
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
				} else {
					result.msg.status = 2;
					result.msg.desc = "验证码错误!";
				}
			} else {
				result.msg.status = 3;
				result.msg.desc = "当前用户不存在";
			}
		} else {
			result.msg.status = -1;
			result.msg.desc = "手机号或验证码不能为空!";
		}
		return result;
	}
	

	/**
	 * IOS找回密码 
	 * 作者：聂紫晨 
	 * 创建时间：2017年5月5日 上午09:55:32
	 */
	@ResponseBody
	@RequestMapping(value = "/findPasswordIOS", method = RequestMethod.POST)
	public ApiResult validateCaptchaIOS(HttpServletRequest request,
			HttpServletResponse response, String datas) {

		ApiResult result = new ApiResult();
		result.msg.status = 1;
		result.msg.desc = "验证失败";
		String reqParam = request.getParameter("datas");
		JSONObject jasonObject = JSONObject.fromObject(reqParam);
		String telphone = (String) jasonObject.get("telphone");
		String validateNum = (String) jasonObject.get("validateNum");
		String password = (String) jasonObject.get("password");

		if (telphone != null && telphone != "" && validateNum != null
				&& validateNum != "") {
			SmsSession ss = smsSessionService.findBySessionId(telphone);
			Admin admin = adminService.findByTelphone(telphone);
//			int reInt;
			if (admin != null) {
				if (ss != null) {
//					try {
//						reInt = smsService.verifySMSCode(ss.getSessionId(),
//								validateNum);
//						if (reInt == 0) {
						if(validateNum.equals(ss.getSessionId())){
							admin.setPassword(DigestUtils.md5Hex(DigestUtils.sha256Hex(password).toUpperCase()));
							int count = adminService.updateAdmin(admin,0);
							if (count > 0) {
								result.msg.status = 0;
								result.msg.desc = "修改成功！";
							} else {
								result.msg.status = 1;
								result.msg.desc = "系统错误，修改失败！";
							}
						} else {
							result.msg.status = 2;
							result.msg.desc = "验证码错误!";
						}
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
				} else {
					result.msg.status = 2;
					result.msg.desc = "验证码错误!";
				}
			} else {
				result.msg.status = 3;
				result.msg.desc = "当前用户不存在";
			}
		} else {
			result.msg.status = -1;
			result.msg.desc = "手机号或验证码不能为空!";
		}
		return result;
	}


	private String getSessionId(HttpServletRequest request,
			HttpServletResponse response, String telphone, String password) {
		String sessionId;
		SafeSession safeSession = safeSessionService.findByAccountAndPassword(telphone,DigestUtils.md5Hex(password));// 判断是否登录过
		if (safeSession != null) {
			sessionId = DigestUtils.md5Hex(telphone) + "_"+ UUID.randomUUID().toString() + "_"+ DigestUtils.md5Hex(password);// 用户名+uuid+密码
			HttpSession session = request.getSession();
			Cookie cookie = new Cookie("dhwx_token", session.getId());
			cookie.setMaxAge(30 * 24 * 60 * 60);// 有效时长30天
			response.addCookie(cookie);
			safeSession.setSessionid(sessionId);
			safeSession.setCreatedate(new Date());
			safeSessionService.update(safeSession);
			session.setAttribute("sessionId", sessionId);
			session.setAttribute("password",safeSession.getPassword());
			session.setAttribute("telphone", telphone);
		} else {
			sessionId = DigestUtils.md5Hex(telphone)+ "_"+ UUID.randomUUID().toString()+ "_"+ DigestUtils.md5Hex(password);// 用户名+uuid+密码
			HttpSession session = request.getSession();
			Cookie cookie = new Cookie("dhwx_token",session.getId());
			cookie.setMaxAge(30 * 24 * 60 * 60);
			response.addCookie(cookie);
			session.setAttribute("sessionId", sessionId);
			session.setAttribute("password",DigestUtils.md5Hex(password));
			session.setAttribute("telphone", telphone);
			SafeSession ssn = new SafeSession();
			ssn.setAccountno(telphone);
			ssn.setCreatedate(new Date());
			ssn.setSessionid(sessionId);
			ssn.setPassword(DigestUtils.md5Hex(password));
			safeSessionService.deleted(telphone);
			safeSessionService.insert(ssn);
		}
		return sessionId;
	}
    private static boolean isNumLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }
}
